from ctypes import windll
import win32gui
import win32con
import win32process


class WindowManager:
    def __init__(self):
        """初始化窗口管理器，设置DPI感知"""
        windll.user32.SetProcessDPIAware()

    def get_foreground_window(self):
        """获取当前活动窗口句柄"""
        return win32gui.GetForegroundWindow()

    def find_window_by_title(self, title, class_name=None):
        """
        通过窗口标题查找窗口句柄
        :param title: 窗口标题
        :param class_name: 窗口类名(可选)
        :return: 窗口句柄，未找到返回0
        """
        return win32gui.FindWindow(class_name, title)

    def get_window_info(self, hwnd):
        """
        获取窗口详细信息
        :param hwnd: 窗口句柄
        :return: 包含窗口信息的字典
        """
        if not win32gui.IsWindow(hwnd):
            return None

        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        _, pid = win32process.GetWindowThreadProcessId(hwnd)

        return {
            'handle': hwnd,
            'title': win32gui.GetWindowText(hwnd),
            'class_name': win32gui.GetClassName(hwnd),
            'rect': {
                'left': left,
                'top': top,
                'right': right,
                'bottom': bottom,
                'width': right - left,
                'height': bottom - top
            },
            'is_visible': win32gui.IsWindowVisible(hwnd),
            'is_enabled': win32gui.IsWindowEnabled(hwnd),
            'process_id': pid
        }

    def enum_windows(self, filter_visible=True, filter_empty_title=True):
        """
        枚举所有窗口
        :param filter_visible: 是否只返回可见窗口
        :param filter_empty_title: 是否过滤无标题窗口
        :return: 窗口信息列表
        """
        windows = []

        def callback(hwnd, _):
            if filter_visible and not win32gui.IsWindowVisible(hwnd):
                return True

            title = win32gui.GetWindowText(hwnd)
            if filter_empty_title and not title:
                return True

            windows.append(self.get_window_info(hwnd))
            return True

        win32gui.EnumWindows(callback, None)
        return windows

    def set_foreground(self, hwnd):
        """将窗口设置为前台窗口"""
        win32gui.SetForegroundWindow(hwnd)

    def show_window(self, hwnd, command):
        """
        控制窗口显示状态
        :param hwnd: 窗口句柄
        :param command:
            SW_HIDE = 0 (隐藏)
            SW_SHOWNORMAL = 1 (正常显示)
            SW_SHOWMINIMIZED = 2 (最小化)
            SW_SHOWMAXIMIZED = 3 (最大化)
            SW_SHOWNOACTIVATE = 4 (显示但不激活)
            SW_RESTORE = 9 (恢复)
        """
        win32gui.ShowWindow(hwnd, command)

    def move_window(self, hwnd, x, y, width, height, repaint=True):
        """
        移动和调整窗口大小
        :param hwnd: 窗口句柄
        :param x: 新X坐标
        :param y: 新Y坐标
        :param width: 新宽度
        :param height: 新高度
        :param repaint: 是否重绘窗口
        """
        win32gui.MoveWindow(hwnd, x, y, width, height, repaint)

    def close_window(self, hwnd):
        """关闭窗口(发送WM_CLOSE消息)"""
        win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

    def get_child_windows(self, parent_hwnd):
        """获取指定窗口的所有子窗口"""
        children = []

        def callback(hwnd, _):
            children.append(self.get_window_info(hwnd))
            return True

        win32gui.EnumChildWindows(parent_hwnd, callback, None)
        return children


# 使用示例
if __name__ == "__main__":
    wm = WindowManager()

    # 获取当前活动窗口
    active_window = wm.get_foreground_window()
    print("当前活动窗口:", wm.get_window_info(active_window))

    # 查找特定窗口
    target_hwnd = wm.find_window_by_title("netCraft Updater")
    if target_hwnd:
        print("找到目标窗口:", wm.get_window_info(target_hwnd))

        # 操作窗口
        wm.set_foreground(target_hwnd)
        wm.move_window(target_hwnd, 100, 100, 800, 600)
    else:
        print("未找到目标窗口")

    # 枚举所有可见窗口
    print("\n所有可见窗口:")
    for window in wm.enum_windows():
        print(f"{window['title']} (Handle: {window['handle']})")